package com.t365.qmm.servlet;

import com.alibaba.fastjson.JSON;
import com.t365.qmm.pojo.*;
import com.t365.qmm.service.BaseOrderService;
import com.t365.qmm.service.GoodsService;
import com.t365.qmm.service.OrderInfoService;
import com.t365.qmm.service.impl.BaseOrderServiceImpl;
import com.t365.qmm.service.impl.GoodsServiceImpl;
import com.t365.qmm.service.impl.OrderInfoServiceImpl;
import com.t365.qmm.utils.Constants;
import com.t365.qmm.utils.RedisUtil;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@WebServlet(name = "OrderServlet", value = "/OrderServlet")
public class OrderServlet extends HttpServlet {
    Jedis jedis = RedisUtil.getJedis();
    BaseOrderService baseOrderService =new BaseOrderServiceImpl();
    OrderInfoService orderInfoService= new OrderInfoServiceImpl();

    GoodsService goodsService =new GoodsServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--------------------------------CartListServlet");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //从redis中请求到该用户的购物车信息
        Integer userId =12 ;//省略session逻辑
        String key = Constants.CART_PREFIX.concat(userId.toString());

        String _totalPrice = request.getParameter("totalPrice");//订单总额为0不能提交订单
        if(null==_totalPrice || "".equals(_totalPrice)){
            out.print(Constants.ERR_MSG_1002);
        }

        addOrder();
        addOrderDetail();
   /*     生成订单
          ①订单主表添加数据
          ②订单明细表添加数据
          ③商品表扣减库存
          ④Redis中清空购物车
          ⑤跳转至用户支付页面
    */
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    public void addOrder(){
        //订单主表
        Integer userId=12;

        BaseOrder record  =new BaseOrder();
        record.setUserId(userId);
        record.setAccount("ck");
        record.setAmount(608.0);
        record.setUserAddress("湖南省郴州市苏仙区第一职中");
        String orderNum = UUID.randomUUID().toString().replace("-","").toUpperCase().concat(userId.toString());
        //System.out.println(orderNum);
        record.setOrderNo(orderNum);
        baseOrderService.insert(record);
        System.out.println(record.getId());
    }

    public void addOrderDetail(){
        //订单明细表 2笔数据
        /*OrderInfo orderInfo = new OrderInfo();
        orderInfo.setGoodsId(734);
        orderInfo.setBuyNum(1);
        orderInfo.setAmount(152.0);
        orderInfo.setBaseOrderId(89);*/
        OrderInfo orderInfo = null;//new OrderInfo();
        String key = Constants.CART_PREFIX.concat("12");
        boolean flag = jedis.exists(key);
        String cart_json = "";
        if (flag) {
            cart_json = jedis.get(key); //获取用户购物车的数据
            CartRedis cartRedis = JSON.parseObject(cart_json, CartRedis.class);//反射
            Map<String, GoodsVo> goodsMap = cartRedis.getGoodsMap();//商品信息

            Iterator<Map.Entry<String, GoodsVo>> its = goodsMap.entrySet().iterator();
            while (its.hasNext()){

                orderInfo =new OrderInfo();
                Map.Entry<String, GoodsVo> goodsEntry = its.next();
                String goodId = goodsEntry.getKey();
                GoodsVo vo = goodsEntry.getValue();

                orderInfo.setGoodsId(Integer.valueOf(goodId));
                orderInfo.setBuyNum(vo.getCount());
                orderInfo.setAmount(vo.getPrice());
                orderInfo.setBaseOrderId(89);

                //根据id获取商品明细
                Goods goods = goodsService.selectByPrimaryKey(Long.valueOf(goodId));
                goods.setStock(goods.getStock()-vo.getCount());//扣减库存

                goodsService.updateByPrimaryKeySelective(goods);

                orderInfoService.insert(orderInfo); //新增订单明细

            }
            goodsMap.clear(); //Redis中清空购物车
            jedis.set(key,JSON.toJSONString(cartRedis));
        }


    }
}
